package cn.zifangsky.jvm.part2.threadlocal;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * 格式化数据
 *
 * @author zifangsky
 * @date 2020/7/11
 * @since 1.0.0
 */
public class ThreadFormat {
    public static ThreadLocal<DecimalFormat> DEFAULT_AMOUNT_FORMAT = ThreadLocal.withInitial(() ->
            new DecimalFormat("#,##0.00")
    );

    public static ThreadLocal<DecimalFormat> DEFAULT_TWO_SCALE_RATIO_FORMAT = ThreadLocal.withInitial(() ->
            new DecimalFormat("0.00%")
    );

    /**
     * 以千分位格式化
     * @param amount amount
     * @return java.lang.String
     */
    public static String thousandthsFormat(BigDecimal amount){
        return DEFAULT_AMOUNT_FORMAT.get().format(amount);
    }

    /**
     * 以百分比格式化
     * @param amount amount
     * @return java.lang.String
     */
    public static String percentageFormat(BigDecimal amount){
        return DEFAULT_TWO_SCALE_RATIO_FORMAT.get().format(amount);
    }


    public static void main(String[] args) {
        BigDecimal amount1 = new BigDecimal("1234.5678");
        BigDecimal amount2 = new BigDecimal("0.345678");

        System.out.println(thousandthsFormat(amount1));
        System.out.println(percentageFormat(amount2));
    }
}
